112. Path Sum - LeetCode Solution


Tree BFS DFS

Python Code:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
        if not root:
            return False
        
        def trav(root, val):
            if not root.right:
                if not root.left:
                    return val + root.val == targetSum
            
            a = False
            b = False
            if root.right:
                a = trav(root.right , val + root.val)
            if root.left:
                b = trav(root.left, val + root.val)
            if a:
                return True
            if b:
                return True
            return False
    
        return trav(root, 0)
                


Comments

Submit
0 Comments
More Questions

1744A - Number Replacement
1744C - Traffic Light
1744B - Even-Odd Increments
637B - Chat Order
546C - Soldier and Cards
18D - Seller Bob
842B - Gleb And Pizza
1746D - Paths on the Tree
1651E - Sum of Matchings
19A - World Football Cup
630P - Area of a Star
1030C - Vasya and Golden Ticket
1529D - Kavi on Pairing Duty
1743A - Password
1743B - Permutation Value
1743C - Save the Magazines
1743D - Problem with Random Tests
1070K - Video Posts
767C - Garland
1201B - Zero Array
1584C - Two Arrays
1131C - Birthday
1285B - Just Eat It
1743F - Intersection and Union
771A - Bear and Friendship Condition
1208E - Let Them Slide
656A - Da Vinci Powers
1025A - Doggo Recoloring
257A - Sockets
231C - To Add or Not to Add